package glpk;

import system.*;
import app.*;

class GlpkFileController {

	GlpkFileService glpkFileService = new GlpkFileService();
	String path = Constants.glpkFileDirectory;

	def index = {
		glpkFileService.processGLPKFile();
		redirect(action:list)
	}

	static transactional = true

	def allowedMethods = []

	def list = {
		def fileResourceInstanceList = []
		def f = new File(path)
		if( f.exists() ){
			f.eachFile(){ file->
				if( !file.isDirectory() )
					fileResourceInstanceList.add( file.name )
			}
		}
		[ fileResourceInstanceList: fileResourceInstanceList ]
	}

	def delete = {
		def filename = params.id.replace('###', '.')
		def file = new File( path + File.separatorChar + filename )
		file.delete()
		flash.message = "file ${filename} removed"
		redirect( action:list )
	}


	def download = {
		def filename = params.id.replace('###', '.');
		def file = new File( path + File.separatorChar + filename );

		try {
			//download
			response.setContentType("application/octet-stream");
			//view
			//response.contentType = "text/plain";
			response.outputStream << file.text;
		}
		catch(Exception e) {
			println(e.message);
		}

		redirect( action:list )
		flash.message = 'file ${filename} downloaded';
	}

	def view = {
		def filename = params.id.replace('###', '.');
		def file = new File( path + File.separatorChar + filename );
		println(filename)
		//download
		//response.setContentType("application/octet-stream");
		//view
		try
		{
			response.contentType = "text/plain";
			response.outputStream << file.text;
		}
		catch(Exception e)
		{
			println(e.message);
		}
		redirect( action:list )
	}
	
	def process = {
		redirect(action:index)
	}
}
